﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ApprovalFlow.Models
{
    public class IfStepDescription : StepDescription, IContainerStepDescription
    {
        private List<ConditionDescription> conditions = new List<ConditionDescription>();

        public ConditionDescription[] Condition { get => this.conditions.ToArray(); }

        public void AddCondition(ConditionDescription condition)
        {
            this.conditions.Add(condition);
        }

        public override IEnumerable<ExecutionPointer> Builder(WorkflowInstance instance, ExecutionPointer master)
        {
            List<ExecutionPointer> pointers = new List<ExecutionPointer>();
            foreach (var condition in this.Condition)
            {
                if (condition.Verify())
                {
                    pointers.AddRange(condition.Builder(instance, master));
                    break;
                }
            }
            if (this.ChildNode is not null)
            {
                var children = this.ChildNode.Builder(instance, pointers.LastOrDefault() ?? master);
                pointers.AddRange(children);
            }
            return pointers;
        }
    }
}
